<?php

namespace App\sender;

use Yurun\Util\HttpRequest;

class Dingding implements Sender
{

    protected $webhook, $secret;

    public function __construct(string $webhook, string $secret)
    {
        $this->webhook = $webhook;
        $this->secret = $secret;
    }

    public function sendNotice(array $params)
    {
        echo "# 推送消息到 钉钉 ..." . PHP_EOL;
        [$timestamp, $signStr] = $this->getQueryParams();
        $uri = "{$this->webhook}&timestamp=$timestamp&sign=$signStr";
        $http = new HttpRequest();
        $resp = $http->post($uri, $params, 'json');
        $body = $resp->json(true);
        if($body['errcode'] === 0){
            echo "^^ 推送成功 Okay" . PHP_EOL;
        }else{
            echo "!! 推送失败：" .$body['errmsg']. PHP_EOL;
        }
    }

    /**
     * 获取 webhook 请求签名参数
     * @return array
     * @author gaolei 2021/9/24 1:20 下午
     */
    function getQueryParams(): array
    {
        list($s1, $s2) = explode(' ', microtime());
        $timestamp = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
        $data = $timestamp . "\n" . $this->secret;
        $signStr = base64_encode(hash_hmac('sha256', $data, $this->secret, true));
        $signStr = utf8_encode(urlencode($signStr));
        return [$timestamp, $signStr];
    }

}